import store from "@/store";
// websocket地址
let url = 'ws://192.168.1.215:8003/chat'
// websocket实例
let ws

let singleReconnect
//重连标识
let websocketSwitch

let token = sessionStorage.getItem("token")

let websocket = {
    //初始化
    init() {
        ws = new WebSocket(url)
        //监听连接
        ws.onopen = () => {
            //连接成功进行用户认证
            if (ws.readyState === 1) {
                this.authentication()
            }
        }

        //监听关闭请求
        ws.onclose = () => {
            //关闭断开重连机制
            websocketSwitch = true
        }

        //异常
        ws.onerror = () => {
            reconnect()
        }

        //通讯消息
        ws.onmessage = (message) => {
            let res = JSON.parse(message.data)
            //心跳消息不做处理
            let obj
            if (res.code === 10002) {
                //监听值回传到vueX
                obj = {
                    msg: res.message,
                    code: res.code
                }
                store.dispatch('asyncUpdateChatMsg', obj)
            } else if (res.code === 10004) {
                obj = {
                    msg: res.message,
                    code: res.code
                }
                store.dispatch('asyncUpdateAddFriendMsg', obj)
            } else if (res.code === 10006) {
                obj = {
                    msg: res.message,
                    code: res.code,
                    userId: res.userId
                }
                store.dispatch('asyncUpdateGroupMsg', obj)
            }
        }
    },
    //发送消息
    send(params) {
        let msg = JSON.stringify(params)
        ws.send(msg)
    },
    //关闭websocket连接
    close() {
        this.removeAuthentication()
        ws.close()
    },
    //认证用户
    authentication() {
        if (token !== '' && token !== undefined && token !== null) {
            let login = {
                code: 10001,
                token: 'Bearer ' + token
            }
            this.send(login)
        }
    },
    //移除认证信息
    removeAuthentication() {
        if (token !== '' && token !== undefined && token !== null) {
            let remove = {
                code: 10003,
                token: 'Bearer ' + token
            }
            this.send(remove)
        }
    },
    //连接群组
    connectionGroup(groupId) {
        if ((groupId !== '' && groupId !== undefined && groupId !== null) && (token !== '' && token !== undefined && token !== null)) {
            let group = {
                code: 10005,
                token: 'Bearer ' + token,
                groupId: groupId
            }
            this.send(group)
        }
    }
}


//监听窗口关闭事件，当窗口关闭时-每一个页面关闭都会触发-扩张需求业务
window.onbeforeunload = function () {
}

//浏览器刷新重新连接
if (window.performance.navigation.type === 1) {
    websocket.init()
}

//重连方法
function reconnect() {
    // 判断是否主动关闭连接
    if (websocketSwitch) {
        return
    }
    // 重连定时器-每次websocket错误方法onerror触发他都会触发
    singleReconnect && clearTimeout(singleReconnect)
    singleReconnect = setTimeout(function () {
        websocket.init()
        websocketSwitch = false
    }, 4000)
}

// 暴露对象
export default websocket